package cn.imu.dao;

import cn.imu.entity.User;

import java.sql.*;

public class LoginDao {
    private static  final String URL="jdbc:mysql://localhost:3306/user_db";
    private static final String USERNAME="root";
    private static final String PWD="yangxinming123";

    //登录
    public static int login(User user) {
        //-1:系统异常，0:用户名或密码有误,1:登录成功
        int result=-1 ;
        Connection connection=null;
        PreparedStatement prepareStatement=null;
        ResultSet rs=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(URL, USERNAME, PWD);
            String sql="select count(*) from user where uname=? and upwd=?";
            prepareStatement= connection.prepareStatement(sql);
            prepareStatement.setString(1, user.getName());
            prepareStatement.setString(2, user.getPwd());
            rs = prepareStatement.executeQuery();
            //只有一条数据，不需要用循环，直接用if语句搞定
            if(rs.next()){
                result=rs.getInt(1);
            }
            if(result>0){
                return 1;//登录成功
            }else{
                return 0;//登录失败（用户名或密码错误）
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return  -1;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return -1;
        }finally {
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(prepareStatement!=null) {
                try {
                    prepareStatement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }
    }
}
